package com.ytf.dogbox.util;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Created by tiwolf on 2018/7/18.
 */

public class FlyTextUtil {

    public static String SDPATH= Environment.getExternalStorageDirectory()+"";
    public static String TXTDIR="/solar/set/";
    public static String SUBMQTT="mqtt";
    public static String FUNCTION="function";
    public static String SET="set";

    //将字符串写入到文本文件中
    public static void writeTxtFile(String strContent,String filePath,String fileName){
        //生成文件夹之后，再生成文件，不然会出现bug
        makeFilePath(filePath,fileName);

        String strFilePath=filePath+fileName;
        //每次写入时，都换行写
        String str=strContent;
        try {
            File file=new File(strFilePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            RandomAccessFile raf=new RandomAccessFile(file,"rwd");
            raf.seek(file.length());
            raf.write(str.getBytes());
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取文件数据
    public static String readFile(String dir,String fileName){
        String res="";
        FileInputStream fis=null;
        File file=new File(dir+TXTDIR+fileName);
        if (!file.exists()){
            return "";
        }

        try {
            fis=new FileInputStream(file);
            byte temp[]=new byte[1024];
            StringBuilder sb=new StringBuilder("");
            int len=0;
            while ((len=fis.read(temp))>0){
                sb.append(new String(temp,0,len));
            }
            res=sb.toString();
            fis.close();
        } catch (Exception e) {
            try {
                if (fis!=null){
                    fis.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return res;
    }

    //删除文件
    public static void deleteFile(String dir){
        File file=new File(dir+TXTDIR+"tiwolf_li.txt");
        file.delete();
    }

    //生成文件
    private static File makeFilePath(String filePath, String fileName) {
        File file=null;
        makeRootDirectory(filePath);
        try {
            file=new File(filePath+fileName);
            if (file.exists()){
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    //生成文件夹
    private static void makeRootDirectory(String filePath) {
        File file=null;
        try {
            file=new File(filePath);
            if (!file.exists()){
                file.mkdir();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
